<!--
  专家页面组织病理
  lzx
  2020年1月13日
  www
  2020.01.16
-->
<template lang="pug">
  el-container
    el-header.header
      title-bg
    el-container
      //el-aside.nav-layout(width="258px")
        nav-menu
      el-main.main-anchor
        //main-content(modularTitle="图像上传")
        //div.chose-anchor(v-if="isAdmin")
          span.chose-label 传输选择：
          el-cascader(
            v-model="patientVal"
           // :options="patientOptions"
            @change="handleChange"
          )
        div.main-content-box
          //p.main-content-title image upload
          el-row(:gutter="28")
            el-col(:span="18")
              el-card.rtc-box
                webrtc(
                  :videoHeight="videoHeight"
                  :roomId="roomId"
                  :user-info="userInfo"
                  @join="onJoinUser"
                  @message="onMessage"
                  @onShare="onShare"
                  @imgMessage="onImgMessage"
                  @stopLive = "stopLive"
                  ref="webrtc"
                )
                div.record-icon(v-show="recDisabled")
                  div.record-circle
            el-col(:span="6")
              el-card.form-card.nav-card
                el-menu(slot="header" mode="horizontal" @select="handleSelect" :default-active="activeIndex").card-title
                  el-menu-item(index="1") 患者信息
                  el-menu-item(index="2") 在线交流
                div.form-box(ref="form" v-show="activeIndex === '1'")
                  el-form(:model="formModel" label-width="120px" size="medium")
                    el-form-item(label="患者姓名：")
                      el-input(v-model="formModel.name" readonly)
                    el-form-item(label="年龄：")
                      el-input(v-model="formModel.age" readonly)
                    el-form-item(label="性别：")
                      el-input(v-model="formModel.sex" disabled)
                    el-form-item(label="申请医师：")
                      el-input(v-model="formModel.doctor" disabled)
                    el-form-item(label="申请时间：")
                      el-input(v-model="formModel.applicationTime" disabled)
                    el-form-item(label="原切片单位：")
                      el-input(v-model="formModel.hospitalName" readonly)
                    el-form-item(label="切片类型：")
                      el-input(v-model="formModel.cname" readonly)
                    el-form-item(label="病理号：")
                      el-input(v-model="formModel.pathologyNum" readonly)
                    el-form-item(label="临床诊断：")
                      el-input(v-model="formModel.diagnosis" readonly)
                    el-form-item(label="肉眼及手术所见：")
                      el-input(v-model="formModel.diagnosisDetail" type="textarea" resize="none" readonly :rows="4")
                div(v-show="activeIndex === '2'")
                  div.chat-box(ref="chatBox")
                    div.chat-list-box
                      div.chat-content(
                        v-for="(item, index) in chatList"
                        :key="index"
                        :class="[{'anchor': item.from.userInfo.identity ==='医生'},{'audience': item.from.userInfo.identity ==='专家' || item.from.userInfo.identity ==='管理专家'}]"
                      )
                        span.person-name 【{{item.from.userInfo.identity}}】 【{{item.from.userInfo.name}}】
                        span(v-if="!item.join") ：
                        span.chat-content {{item.content}}
                        el-card.chat-img-box(v-if="item.imgSrc")
                          img.chat-img(:src="item.imgSrc" @click="showPic(item.imgSrc)")
                        el-dialog(:visible.sync="imgDialogVisible")
                          img(width="100%" :src="dialogImageUrl")
                    el-row(:gutter="10")
                      el-col(:span="17")
                        el-input.chat-input(v-model="chatContent")
                      el-col(:span="4")
                        el-button.long(@click="sendMessage" type="primary") 发送
                        input.img-btn-hidden(
                          type="file"
                          id="id"
                          name="image"
                          class="getImgUrl_file"
                          @change="sendImg($event)"
                          accept="image/jpg,image/jpeg,image/png"
                          ref="imgFile"
                        )
                      el-col(:span="3")
                        el-button(@click="sendPicture" icon="el-icon-picture-outline" type="primary")
              el-card.person-list-box
                //el-popover(
                  placement="top-start"
                  trigger="click"
                  width="250"
                //)
                  div.person-popover-box
                    div.person-info-box(v-for="(item, index) in personList" :key="index")
                      img.person-info-avatar(:src="item.userInfo.icon")
                      div.person-info
                        p.person-name {{item.userInfo.name}}
                        p.person-department {{item.userInfo.identity}} | {{item.userInfo.hospital | ellipsis}}
                  div.person-list.float-left(slot="reference")
                    img.person-avatar(v-for="(item, index) in personList" :key="index" :src="item.userInfo.icon")
                div.float-right
                  el-button.invite(size="small" @click="onInvite" v-if="isAdmin") 邀请他人进入会诊
                  el-button(size="small" type="primary" @click="onJoin") 接收会诊
                  el-button(size="small" type="primary" @click="toImage") 采图
                  el-button(size="small" type="primary" @click="startRecording" :disabled="recDisabled") 录制视频
                  el-button.stop-live(size="small" @click="stopRecording" :disabled="!recDisabled") 停止录制
                  el-button.stop-live(size="small" @click="onDiagnose") 会诊诊断
                  el-button.stop-live(size="small" @click="onLeave") 停止会诊
                div.clear
    el-dialog(title="请选择要邀请的专家"
      :visible.sync="dialogVisible"
      width="30%"
      center)
      el-cascader.long(
        v-model="expertVal"
        :options="expertOptions"
        @change="choseDoctor"
      )
      div.dialog-footer(slot="footer")
        el-button(@click="onCancle" type="primary") 取消
        el-button(@click="onSubmit" type="primary") 确认

</template>

<script>
  import TitleBg from '../../components/TitleBg'
  import NavMenu from '../../components/NavMenu'
  import MainContent from '../../components/MainContent'
  import Webrtc from '../../components/webrtc'
  import RecordRTC from 'recordrtc'

  export default {
    components: {
      Webrtc,
      MainContent,
      NavMenu,
      TitleBg
    },
    name: 'audience',
    data() {
      return {
        fullHeight: document.documentElement.clientHeight, // 屏幕可视区域高度
        formModel: {}, // 患者信息表单数据
        videoHeight: null, // 视频高度
        personList: [], // 加入直播用户列表
        activeIndex: '1', // 聊天室与患者信息当前显示
        chatList: [], // 聊天内容数组
        chatContent: '', // 每个人的聊天内容
        roomId: '', // 直播间ID
        userInfo: {
          id: JSON.parse(this.$KalixCatch.get('personaltwo'))[0].id,
          name: JSON.parse(this.$KalixCatch.get('personaltwo'))[0].name,
          identity: JSON.parse(this.$KalixCatch.get('personaltwo'))[0].identity,
          title: JSON.parse(this.$KalixCatch.get('personaltwo'))[0].title,
          icon: JSON.parse(this.$KalixCatch.get('personaltwo'))[0].icon,
          hospital: JSON.parse(this.$KalixCatch.get('personaltwo'))[0].hospital,
          hospitalId: JSON.parse(this.$KalixCatch.get('personaltwo'))[0].hospitalId,
          isShare: 'stop'
        }, // 当前用户信息
        video: null, // 视频录制器
        recorder: null, // rtcrecord对象
        patientVal: [], // 选中的患者
        patientOptions: [], // 所有患者选项
        dialogVisible: false, // 邀请专家弹窗是否显示
        expertVal: [], // 邀请的专家
        expertOptions: [], // 邀请专家级联选项
        expertId: null, // 专家ID——传入后台
        patientId: null, // 选中的患者ID
        isAdmin: true, // 当前用户是否为管理员
        identity: [], // 当前用户身份信息
        imgDialogVisible: false, // 聊天室图片点击放大
        dialogImageUrl: '', // 聊天室图片路径
        recDisabled: false, // 录制/停止录制按钮是否显示
        recordMedia: [] // 录制媒体流
      }
    },
    mounted() {
      this.video = document.querySelector('#record')
      // 身份验证
      this.identity = JSON.parse(this.$KalixCatch.get('personaltwo'))
      console.log('------identity------', this.identity)
      if (this.identity[0].identity === '管理专家') {
        this.getAllPatients()
      } else if (this.identity[0].identity === '医生' || this.identity[0].identity === '专家') {
        this.isAdmin = false
        this.getPatientData(this.$route.query.patientId)
        this.roomId = this.$route.query.patientId + ''
      }
      const that = this
      // 窗口变化重新计算高度
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight
          that.fullHeight = window.fullHeight
          that.$nextTick(() => {
            that.videoHeight = that.fullHeight - 154 + 'px' // 视频高度
            that.$refs.form.style.height = that.fullHeight - 278 - 33 + 'px' // 患者详情表单高度
            that.$refs.chatBox.style.height = that.fullHeight - 278 - 33 + 'px' // 患者详情表单高度
          })
        })()
      }
      this.$nextTick(() => {
        that.videoHeight = that.fullHeight - 154 + 'px' // 视频高度
        that.$refs.form.style.height = that.fullHeight - 278 - 33 + 'px'// 患者详情表单高度
        that.$refs.chatBox.style.height = that.fullHeight - 278 - 33 + 'px'// 患者详情表单高度
      })
    },
    // 字符串超出长度显示...
    filters: {
      ellipsis(value) {
        if (!value) return ''
        if (value.length > 10) {
          return value.slice(0, 10) + '...'
        }
        return value
      }
    },
    beforeRouteLeave(to, from, next) {
      this.onLeave()
      setTimeout(() => {
        next(true)
      }, 1000)
    },
    watch: {
      // 监听屏幕可视区域高度变化
      fullHeight(val) {
        // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
        if (!this.timer) {
          // 一旦监听到的fullHeight值改变，就将其重新赋给data里的fullHeight
          this.fullHeight = val
          this.timer = true
          let that = this
          setTimeout(function () {
            that.timer = false
          }, 400)
        }
      }
    },
    methods: {
      // 病人信息/聊天切换
      handleSelect(key, keyPath) {
        console.log(key, keyPath)
        this.activeIndex = key
      },
      // 创建直播间
      onJoin() {
        this.$refs.webrtc.leave()
        setTimeout(() => {
          this.$refs.webrtc.join()
        }, 500)
      },
      // 停止直播
      onLeave() {
        this.$refs.webrtc.leave()
        this.personList.map(item => {
          if (item.userInfo.id === this.userInfo.id) {
            this.personList.splice(item, 1)
          }
        })
      },
      // 会诊诊断
      onDiagnose() {
        let routeData = this.$router.resolve({ path: '/diagnose' })
        window.open(routeData.href, '_blank')
      },
      // 接收并显示直播间加入用户
      onJoinUser(personList) {
        console.log('------personList------', personList)
        this.personList = personList
      },
      // 接收并显示聊天文字信息
      onMessage(message) {
        console.log(message)
        this.chatList.push(message)
      },
      // 接收并显示聊天图片信息
      onImgMessage(imgMessage, type) {
        this.chatList.push(imgMessage)
      },
      // 接收屏幕共享信息并传入组件
      onShare(message, stream, type) {
        console.log('stream------', stream)
        this.$refs.webrtc.shareChange(message, stream)
      },
      // 发送文字信息
      sendMessage() {
        let str = this.chatContent.replace(/(^\s*)|(\s*$)/g, '')
        if (str) {
          let message = {
            from: {
              userInfo: this.userInfo
            },
            content: this.chatContent
          }
          this.$refs.webrtc.sendMessage(message)
          this.chatList.push(message)
          this.chatContent = ''
        }
      },
      // 发送图片信息
      /* eslint-disable */
      sendImg(e) {
        let files = document.getElementById('id').files[0]
        let name = document.getElementById('id').files[0].name
        let arr = name.split('.')
        console.log(arr)
        let fileSize = 0
        let fileMaxSize = 10240//1M
        if (files) {
          fileSize = files.size
          if (fileSize > 10 * 1024 * 1024) {
            alert('文件大小不能大于10M！')
            file.value = ''
            return false
          } else if (fileSize <= 0) {
            alert('文件大小不能为0M！')
            file.value = ''
            return false
          }
        } else {
          return false
        }

        //转码base64
        let reader = new FileReader()
        let imgFile
        let that = this
        reader.readAsDataURL(files)
        reader.onload = e => {
          imgFile = e.target.result
          let imgMessage = {
            from: {
              userInfo: this.userInfo
            },
            imgSrc: imgFile
          }
          that.$refs.webrtc.sendImg(imgMessage)
          this.chatList.push(imgMessage)
        }
        this.$refs.imgFile.value = ''
      },
      // 发送图片按钮调用input获取本体图片功能
      sendPicture() {
        this.$refs.imgFile.dispatchEvent(new MouseEvent('click'))
      },
      // 开始录制
      startRecording() {
        // console.log(this.video)
        this.recDisabled = true
        let that = this
        this.recordMedia = []
        this.$refs.webrtc.videoList.forEach(item => {
          that.recordMedia.push(item.stream)
        })
        this.recorder = RecordRTC(this.recordMedia, {
          type: 'video',
          mimeType: 'video/mp4',
          video: {
            width: 1920,
            height: 1080
          }
        })
        this.recorder.startRecording()
      },
      handleError(err) {
        console.log('getUserMedia error:', err)
      },
      // 停止录制将视频保存到本地
      stopRecordingCallback() {
        this.recDisabled = false
        this.video.src = this.video.srcObject = null
        this.video.muted = false
        this.video.volume = 1
        this.video.src = URL.createObjectURL(this.recorder.getBlob())
        window.open(URL.createObjectURL(this.recorder.getBlob()))
        const a = document.createElement('a')
        a.style.display = 'none'
        a.download = '<文件名>'
        a.href = this.video.src
        a.click()
        // let fileName = this.getFileName('webm')
        // let fileObject = new File([this.recorder.getBlob()], fileName, {
        //   type: 'video/webm'
        // })
        // let formData = new FormData()
        // recorded data
        // formData.append('video-blob', fileObject)
        // file name
        // formData.append('video-filename', fileObject.name)
        // let request = new XMLHttpRequest()
        // request.open('post', 'https://192.168.31.92:443/upload')
        // request.send(formData)
        // request.onreadystatechange(() => {
        //   if (request.readyState === 4 && request.status === 200) {
        //     alert(request.responseText)
        //   } else {
        //     alert(request.statusText)
        //   }
        // })
        this.recorder.destroy()
        this.recorder = null
      },
      getFileName(fileExtension) {
        let d = new Date()
        let year = d.getUTCFullYear()
        let month = d.getUTCMonth()
        let date = d.getUTCDate()
        return (
          'RecordRTC-' +
          year +
          month +
          date +
          '-' +
          this.getRandomString() +
          '.' +
          fileExtension
        )
      },
      stopRecording() {
        this.recorder.stopRecording(this.stopRecordingCallback)
      },
      // 选择要加入的直播间
      handleChange(value) {
        console.log(value)
        this.patientId = value[2]
        this.roomId = this.patientId + ''
        this.getPatientData(this.patientId)
      },
      // 选择要邀请的专家
      choseDoctor(value) {
        console.log('value---------------', value)
        this.expertId = value[1]
      },
      // 视频截图
      toImage() {
        console.log(this.$refs.webrtc.videoList)
        let videoArray = this.$refs.webrtc.videoList
        let videoId = null
        videoArray.forEach(item => {
          if (item.isAudio === false) {
            videoId = item.id
          }
        })
        let video = document.getElementById(videoId)
        let canvas = document.createElement('canvas')
        // canvas.width = video.videoWidth
        // canvas.height = video.videoHeight
        let maxWidth = 800
        let maxHeight = 800
        if(video.videoWidth > maxWidth || video.videoHeight > maxHeight) {
          if(video.videoWidth / video.videoHeight > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            canvas.width = maxWidth
            canvas.height = Math.round(maxWidth * (video.videoHeight / video.videoWidth))
          } else {
            canvas.height = maxHeight
            canvas.width = Math.round(maxHeight * (video.videoWidth / video.videoHeight))
          }
        }
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
        let Url = canvas.toDataURL('image/png', 1.0)
        let arr = Url.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        let blob = new Blob([u8arr], {
          type: mime
        })
        let imgUrl = window.URL.createObjectURL(blob)
        let a = document.createElement('a')
        a.style.display = 'none'
        a.href = imgUrl
        a.download = '会诊影像采图'
        document.body.appendChild(a)
        a.click()
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(imgUrl);
        }, 1000)
      },
      // 邀请他人加入会诊
      onInvite() {
        this.dialogVisible = true
        this.getAllExpert()
      },
      // 邀请专家弹窗取消
      onCancle() {
        this.dialogVisible = false
      },
      // 邀请专家提交
      onSubmit() {
        if (!this.patientId) {
          this.$message({
            message: '请选择会诊的患者',
            type: 'error'
          })
        } else {
          this.$http.request({
            method: 'POST',
            url: 'camel/rest/telemedicine/lives',
            data: {
              expertId: this.expertId,
              fileId: this.patientId
            }
          }).then(res => {
            this.dialogVisible = false
            this.doctorInviteVal = []
          })
        }
      },
      // 聊天图片点击放大
      showPic(imgSrc) {
        this.dialogImageUrl = imgSrc
        this.imgDialogVisible = true;
      },
      // 管理专家获取所有患者信息
      getAllPatients() {
        this.$http.request({
          method: 'GET',
          url: 'camel/rest/telemedicine/lives/getValue',
        }).then(res => {
          let _data = res.data.data
          console.log('------AllPatient------', _data)
          this.patientOptions = _data
        })
      },
      // 获取所有专家信息
      getAllExpert() {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/lives/getExpertValue',
        }).then(res => {
          let _data = res.data.data
          console.log('------AllExpert------', _data)
          this.expertOptions = _data
        })
      },
      // 获取当前患者信息
      getPatientData(patientId) {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/files/getPatient',
          params: {
            patientId: patientId
          }
        }).then(res => {
          let _data = res.data.data[0]
          console.log('------PatientData------', _data)
          this.formModel = _data
          this.formModel.sex === 1 ? this.formModel.sex = '男' : this.formModel.sex = '女'
        })
      },
      // 医生停止直播后刷新页面
      stopLive(roomId) {
        console.log(roomId)
        if (this.roomId === roomId) {
          // 跳到首页
          this.$router.push({ path:'/expertOrg'  })
          // 页面刷新
          // this.$router.go(0)
        }
      }
    }
  }
</script>

<style scoped lang="stylus">
  .el-button
    padding 12px 8px
  .el-button+.el-button
    margin-left 4px
  .header
    padding 0

  .nav-layout
    position relative
    height 100%

  .main-anchor
    margin-left 27px
    padding 0

    .chose-anchor
      position absolute
      top 10px
      right 50px

      .chose-label
        color #fff
        font-size 14px

      .el-cascader
        width 375px

    .main-content-box
      padding-right 27px
      margin-top 0
      overflow-y auto
      overflow-x hidden

      .main-content-title
        color #a2c8f8
        font-size 14px

      .el-card
        margin-top 25px

        .card-title
          font-size 16px

      .person-list-box
        margin-top 25px
        cursor pointer

        .person-list
          .person-avatar
            width 30px
            height 30px
            border-radius 50%
            display inline-block
            vertical-align middle
            margin 0 5px

      .stop-live
        background-color #6861ce
        color #fff

      .stop-live:hover
        opacity 0.8

      .invite
        background-color #1a2035
        color #fff

      .invite:hover
        opacity 0.8

  .form-card
    .el-form-item
      margin-bottom 17px

  .person-popover-box
    .person-info-box
      margin 5px 0

      .person-info-avatar
        width 46px
        height 46px
        display inline-block
        vertical-align middle

      .person-info
        display inline-block
        vertical-align middle
        margin-left 10px

        .person-name
          font-size 18px
          color #575962

        .person-department
          font-size 14px
          color #bbbbbb

  .chat-img-box
    display inline-block
    vertical-align top
    margin-top 0 !important
    cursor pointer

  .chat-img
    vertical-align top
    display inline-block
    max-height 100px
    max-width 200px

  .img-btn-hidden
    display none

  .chat-list-box
    width 100%
    padding 15px
    height 90%
    border 3px solid #1269db
    border-radius 8px
    margin-bottom 20px
    box-sizing border-box
    overflow auto
    font-size 14px

  .anchor
    color blue

  .audience
    color #ffa315

  .long
    width 100%

  .rtc-box
    position relative

  .record-icon
    width 20px
    height 20px
    border-radius 50%
    position absolute
    top 30px
    right 30px
    border 1px solid red
    box-sizing border-box

  .record-circle
    width 16px
    height 16px
    background-color red
    border-radius 50%
    margin auto
    margin-top 1px

  .form-box
    overflow auto
</style>
